#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/serial.h>
#include <linux/gpio.h>
#include <linux/gpio.h>

int main(int argc, char *argv[])
{
    struct gpiohandle_request req;
    struct gpiohandle_data data;
    int gpiochip = 0;
    int gpionum = 0;
    int outValue = 0;
    int u_sleep = 0;
    int ret;
    int fd = -1;
    char devPath[32] = {'\0'};

    if(argc == 5) {
        gpiochip = atoi(argv[1]);
        gpionum = atoi(argv[2]);
        outValue = atoi(argv[3]);
        u_sleep = atoi(argv[4]);
    }
    printf("GpioChip:[%d] gpionum:[%d]\n", gpiochip, gpionum);

    sprintf(devPath, "/dev/gpiochip%d", gpiochip);
    printf("devPath : %s\n", devPath);
    fd = open(devPath, 0);
    if (fd == -1) {
        fprintf(stderr, "Failed to open %s\n",devPath);
        exit(1);
    }
    /* request GPIO line: GPIO_D_12 */
    req.lineoffsets[0] = gpionum;
    req.flags = GPIOHANDLE_REQUEST_OUTPUT;  //output 
    //memcpy(req->default_values, data, sizeof(req->default_values));
    strcpy(req.consumer_label, "rs485_gpio");
    req.lines = 1;
    ret = ioctl(fd, GPIO_GET_LINEHANDLE_IOCTL, &req);
    if (ret == -1) {
        fprintf(stderr,"Failed to issue GET LINEHANDLE IOCTL (%d)\n",ret);
    }

    // 设置GPIO引脚的值
    data.values[0] = outValue;
    ioctl(req.fd, GPIOHANDLE_SET_LINE_VALUES_IOCTL, &data);
    usleep(u_sleep);

    // 读取GPIO引脚的值
    ioctl(req.fd, GPIOHANDLE_GET_LINE_VALUES_IOCTL, &data);
    printf("The GPIO value: %d\n", data.values[0]);

    // 关闭GPIO设备
    close(req.fd);
    close(fd);

    return 0;
}